﻿

using COVID_19_LiquidFillUI.Common.Services;
using COVID_19_LiquidFillUI.Models;
using HalconDotNet;
using NLog;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ViewROI;
using DialogResult = System.Windows.Forms.DialogResult;
using MessageBox = System.Windows.Forms.MessageBox;

namespace COVID_19_LiquidFillUI.ViewModels.Dialogs
{
    public class Station1CameraCalcDialogViewModel : DialogViewModel
    {
        #region 变量
        ICameraService cam;
        int cameraIndex = 0;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private readonly IContainerProvider _containerProvider;
        #endregion
        #region 属性绑定
        #region halcon
        #region 1#
        private HImage cameraIamge0;
        public HImage CameraIamge0
        {
            get { return cameraIamge0; }
            set { SetProperty(ref cameraIamge0, value); }
        }
        private bool cameraRepaint0;
        public bool CameraRepaint0
        {
            get { return cameraRepaint0; }
            set { SetProperty(ref cameraRepaint0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        #endregion
        #endregion
        private int thresholdMin;
        public int ThresholdMin
        {
            get { return thresholdMin; }
            set { SetProperty(ref thresholdMin, value); }
        }
        private int tresholdMax;
        public int ThresholdMax
        {
            get { return tresholdMax; }
            set { SetProperty(ref tresholdMax, value); }
        }
        private int judgeArea;
        public int JudgeArea
        {
            get { return judgeArea; }
            set { SetProperty(ref judgeArea, value); }
        }
        private ObservableCollection<DispVisionPoint1> pointList1;
        

        public ObservableCollection<DispVisionPoint1> PointList1
        {
            get { return pointList1; }
            set { SetProperty(ref pointList1, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<object> cameraOperateCommand;
        public DelegateCommand<object> CameraOperateCommand =>
            cameraOperateCommand ?? (cameraOperateCommand = new DelegateCommand<object>(ExecuteCameraOperateCommand));
        private DelegateCommand<DispVisionPoint1> pointList1SelectCommand;
        public DelegateCommand<DispVisionPoint1> PointList1SelectCommand =>
            pointList1SelectCommand ?? (pointList1SelectCommand = new DelegateCommand<DispVisionPoint1>(ExecutePointList1SelectCommand));
        private DelegateCommand<DispVisionPoint1> createRec1Command;
        public DelegateCommand<DispVisionPoint1> CreateRec1Command =>
            createRec1Command ?? (createRec1Command = new DelegateCommand<DispVisionPoint1>(ExecuteCreateRec1Command));
        private DelegateCommand<DispVisionPoint1> updateCommand;
        public DelegateCommand<DispVisionPoint1> UpdateCommand =>
            updateCommand ?? (updateCommand = new DelegateCommand<DispVisionPoint1>(ExecuteUpdateCommand));
        private DelegateCommand calcCommand;
        public DelegateCommand CalcCommand =>
            calcCommand ?? (calcCommand = new DelegateCommand(ExecuteCalcCommand));

        void ExecuteCalcCommand()
        {
            if (CameraIamge0 != null)
            {
                string filepath = $"Camera\\{cameraIndex}";
                CameraAppendHMessage0 = null;
                CameraAppendHObject0 = null;
                try
                {
                    bool totalResult = true;
                    foreach (var item in PointList1)
                    {
                        HObject rec1;
                        HOperatorSet.ReadRegion(out rec1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, $"rec1_{item.PcsOrder}.hobj"));

                        HObject ho_resultRegion; HTuple hv_result, mArea;
                        ImageCalc.AreaCalc(CameraIamge0, rec1, item.ThresholdMin, item.ThresholdMax, item.JudgeArea, out ho_resultRegion, out hv_result, out mArea);
                        
                        HTuple msgRow, mesColumn;
                        HOperatorSet.RegionFeatures(rec1,"row", out msgRow);
                        HOperatorSet.RegionFeatures(rec1, "column", out mesColumn);
                        CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)msgRow.D, (int)mesColumn.D, "black", "image", "box", "true", 12, "mono", "true", "false");
                        if (hv_result == 1)
                        {
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                            CameraAppendHObject0 = ho_resultRegion;
                        }
                        else
                        {
                            totalResult = false;
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                            CameraAppendHObject0 = rec1;
                        }
                        
                    }
                    if (totalResult)
                    {
                        CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                    }
                    else
                    {
                        CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
           

        }
        void ExecuteUpdateCommand(DispVisionPoint1 point)
        {
            if (point != null)
            {
                using var mdb = new MDbContext();
                var _point0 = mdb.MVisionPoint1s.FirstOrDefault(p => p.PcsOrder == point.PcsOrder && p.Kind == cameraIndex);
                if (_point0 != null) 
                {
                    _point0.ThresholdMin = point.ThresholdMin = ThresholdMin;
                    _point0.ThresholdMax = point.ThresholdMax = ThresholdMax;
                    _point0.JudgeArea= point.JudgeArea = JudgeArea;
                    mdb.SaveChanges();
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteCreateRec1Command(DispVisionPoint1 point)
        {
            if (point != null)
            {
                if (CameraIamge0 != null)
                {
                    string filepath = $"Camera\\{cameraIndex}";
                    if (MessageBox.Show($"你确定画相机{cameraIndex + 1}的\"{point.PcsOrder}\"区域吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        try
                        {
                            var roi = Global.CameraImageViewer1.DrawROI(ROI.ROI_TYPE_RECTANGLE1);
                            var rec1 = roi.getRegion();

                            DirectoryInfo dir = new DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                            if (!dir.Exists)
                            {
                                Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                            }
                            HOperatorSet.WriteRegion(rec1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, $"rec1_{point.PcsOrder}.hobj"));
                            CameraAppendHMessage0 = null;
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "orange red");
                            CameraAppendHObject0 = null;
                            CameraAppendHObject0 = rec1;
                            HObject ho_resultRegion; HTuple hv_result, mArea;
                            ImageCalc.AreaCalc(CameraIamge0, rec1, point.ThresholdMin, point.ThresholdMax, point.JudgeArea, out ho_resultRegion, out hv_result,out mArea);
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                            CameraAppendHMessage0 = new HMsgEntry($"{mArea.D:f0}", 40, 10, "medium blue", "window", "box", "false", 32, "mono", "true", "false");
                            if (hv_result == 1)
                            {
                                CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");                                
                                CameraGCStyle0 = new Tuple<string, object>("Color", "green");                                
                            }
                            else 
                            {
                                CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                                CameraGCStyle0 = new Tuple<string, object>("Color", "red");                                
                            }
                            CameraAppendHObject0 = ho_resultRegion;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecutePointList1SelectCommand(DispVisionPoint1 point)
        {
            if (point != null)
            {
                ThresholdMin = point.ThresholdMin;
                ThresholdMax = point.ThresholdMax;
                JudgeArea= point.JudgeArea;
            }
        }
        void ExecuteCameraOperateCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "拍照":                    
                    CameraIamge0 = cam.GrabImage();
                    break;
                case "打开":
                    {
                        OpenFileDialog openFileDialog = new OpenFileDialog();
                        openFileDialog.Filter = "Image Files|*.png;*.bmp;*.jpg;*.tif";
                        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            HObject image;
                            HOperatorSet.ReadImage(out image, openFileDialog.FileName);
                            CameraIamge0 = new HImage(image);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            cameraIndex = parameters.GetValue<int>("CameraIndex");
            Title = $"相机{cameraIndex + 1}";
            switch (cameraIndex)
            {
                case 0:
                    cam = _containerProvider.Resolve<ICameraService>("Cam0");
                    break;
                case 1:
                    cam = _containerProvider.Resolve<ICameraService>("Cam1");
                    break;
                default:
                    break;
            }
            using var mdb = new MDbContext();
            var points0 = mdb.MVisionPoint1s.Where(p => p.Kind == cameraIndex);
            if (points0.Any())
            {
                var points1 = points0.OrderBy(p => p.PcsOrder).ToList();
                foreach (var item in points1)
                {
                    PointList1.Add(new DispVisionPoint1 { 
                        PcsOrder= item.PcsOrder,
                        ThresholdMax=item.ThresholdMax,
                        ThresholdMin=item.ThresholdMin,
                        JudgeArea=item.JudgeArea
                    });
                }
            }
        }
        #endregion
        #region 构造函数
        public Station1CameraCalcDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            _containerProvider = containerProvider;
            PointList1 = new ObservableCollection<DispVisionPoint1>();
           
        }
        #endregion

    }
}
